package com.xinke.edu.mypetadoption.fragment2.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.xinke.edu.mypetadoption.R;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.xinke.edu.mypetadoption.fragment2.adapter.CategoryAdapter;
import com.xinke.edu.mypetadoption.databinding.ActivtySjFbspBinding;
import com.xinke.edu.mypetadoption.entity.ProductCategory;
import com.xinke.edu.mypetadoption.entity.ResultBody;
import com.xinke.edu.mypetadoption.net.RetrofitUtil;
import com.xinke.edu.mypetadoption.util.GlideEngine;
import com.xinke.edu.mypetadoption.util.SPUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class Sj_FbProductActivity extends AppCompatActivity {
    ActivtySjFbspBinding binding;
    CategoryAdapter mAdapter;
    int categoryId = 1;
    String path = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivtySjFbspBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());
        getType();

        binding.exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.rlImgContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureSelector.create(Sj_FbProductActivity.this)
                        .openGallery(SelectMimeType.ofImage())
                        .setMaxSelectNum(1)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                if (result.size() > 0) {
                                    path = result.get(0).getRealPath();
                                    Glide.with(Sj_FbProductActivity.this).load(path).into(binding.ivGoodsImg);
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });

        binding.btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pubProduct();
            }
        });
    }


    public void getType() {
                RetrofitUtil.getApi().getType()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBody<List<ProductCategory>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResultBody<List<ProductCategory>> listResultBody) {
                        List<ProductCategory> datas = listResultBody.getData();
                        mAdapter = new CategoryAdapter(Sj_FbProductActivity.this, datas);
                        binding.spGoodsCategory.setAdapter(mAdapter);
                        // 设置下拉列表的样式
                        mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        // 设置选择事件监听
                        binding.spGoodsCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                // 获取选中的分类对象
                                ProductCategory selectedCategory = datas.get(position);
                                // 获取ID和名称
                                categoryId = selectedCategory.getId();
//                                String categoryName = selectedCategory.getName();

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                // 未选择时的处理（可选）
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(Sj_FbProductActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void pubProduct() {
        String name = binding.etGoodsName.getText().toString();
        String price = binding.etGoodsPrice.getText().toString();
        String stock = binding.etStock.getText().toString();
        String desc = binding.etGoodsDesc.getText().toString();

        // 表单验证
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "商品名字不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(price)) {
            Toast.makeText(this, "价格不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(stock)) {
            Toast.makeText(this, "库存不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(desc)) {
            Toast.makeText(this, "描述不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(path)) {
            Toast.makeText(this, "图片不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        
        try {
            // 创建文件对象
            File file = new File(path);
            
            // 创建图片请求体
            RequestBody requestFile = RequestBody.create(file,
                    MediaType.parse("image/*"));
            
            // 创建MultipartBody.Part对象，用于上传图片
            MultipartBody.Part imagePart = MultipartBody.Part.createFormData(
                    "image",
                    file.getName(),
                    requestFile);

            // 创建文本请求体
            RequestBody nameBody = RequestBody.create(name,
                    MediaType.parse("text/plain"));
            
            RequestBody descBody = RequestBody.create(desc,
                    MediaType.parse("text/plain"));
            
            // 从SPUtils获取商家ID
            Long userId = SPUtils.getInstance(this).getLong("userId", 0);
            
            if (userId <= 0) {
                Toast.makeText(this, "商家ID获取失败，请重新登录", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 调用发布商品接口
            RetrofitUtil.getApi().publishProduct(
                    userId,                // 商家ID
                    nameBody,              // 商品名称
                    categoryId,            // 分类ID
                    Double.parseDouble(price), // 价格
                    Integer.parseInt(stock),   // 库存
                    descBody,              // 描述
                    imagePart              // 图片
            )
            .subscribeOn(Schedulers.io())           // 在IO线程执行网络请求
            .observeOn(AndroidSchedulers.mainThread()) // 在主线程处理响应
            .subscribe(new Observer<ResultBody>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    // 可以在这里添加加载动画
                }

                @Override
                public void onNext(@NonNull ResultBody resultBody) {
                    Toast.makeText(Sj_FbProductActivity.this, resultBody.getMessage(), Toast.LENGTH_SHORT).show();
                    // 如果发布成功，清空表单并返回
                    if (resultBody.getCode() == 200) {
                        // 清空表单
                        binding.etGoodsName.setText("");
                        binding.etGoodsPrice.setText("");
                        binding.etStock.setText("");
                        binding.etGoodsDesc.setText("");
                        binding.ivGoodsImg.setImageResource(R.mipmap.home); // 重置图片
                        path = ""; // 清空图片路径
                        
                        // 延迟返回上一页
                        binding.getRoot().postDelayed(() -> finish(), 1500);
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    Toast.makeText(Sj_FbProductActivity.this, "发布失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete() {
                    // 可以在这里移除加载动画
                }
            });
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "发布失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
}